//
//  LBTILiveManager.m
//  LBTILiveSDK
//
//  Created by 刘文扬 on 2018/3/13.
//

#import "LBTILiveManager.h"


static NSString * const ShowAppId = @"1400074608";

static NSString * const ShowAccountType = @"17805";

@interface LBTILiveManager()

/** cameraPosition*/
@property(nonatomic,assign)cameraPos pos;


@end

@implementation LBTILiveManager


+(instancetype)shareManager
{
    static __kindof LBTILiveManager *sharedManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedManagerInstance=[[super allocWithZone:NULL] init];
    });
    
    return sharedManagerInstance;
}

-(instancetype)init
{
    self = [super init];
    if (self) {
        
        _pos = CameraPosFront;
    }
    return self;
}

-(void)login
{
    if ([UIScreen mainScreen].bounds.size.width == 375) {
        [[ILiveLoginManager getInstance] iLiveLogin:@"32012" sig:@"eJxlj11LwzAARd-7K0JeK5qkTV192xdu2A26ysaeQkyyNi2moY2zIv53Zx0Y8L6ec7nczwAAAJ*z4pYL0b4Zx9yHVRA8AIjgzR*0VkvGHYs6*Q*qwepOMX5yqhshppQShHxHS2WcPumrERGEiYd72bBx47cfX8r3cYImvqLLEW6Wx-k6n6cilItktz8IXJybEB0zzUlZ4MU2XEUm7QZU0zYhts6n62r61MSHYlIvh9mmuBNZVbrVvlc8L99n2Bplt416CR9zuUsrb9LpV3U9RFAaURqnHj2rrtetGYXLHYpJhH4Cg6-gG6yLW1E_" succ:^{
            NSLog(@"登录成功");
        } failed:^(NSString *module, int errId, NSString *errMsg) {
            NSLog(@"登录失败");
        }];
    }else if([UIScreen mainScreen].bounds.size.width == 320){
        
        [[ILiveLoginManager getInstance] iLiveLogin:@"32014" sig:@"eJxlj11LwzAYhe-7K0KvRfLR2Cp4UWqR1k1WnE68CXVN49vNJqSpm4j-fbMODHhun*dwOF8BQihczh7O6-Vaj70T7tPIEF2hEIdnf9AYaETtBLPNPyj3BqwUdeuknSDhnFOMfQca2Tto4WQwiknk4aHZiGnjtx8dy3F0gRNfATXBef6YFWlrLheG7oe*yhSsxrtitnQW3-KO4l0BWbfdli9gzdzgFPKU3b89W5kovWlMvrI63tX16w3vRsV09cRIBWpRJm0Ul*ram3TwLk*HKCExYTH36Ie0A*h*Eo53OKEM-yQMvoMDmNxcvg__" succ:^{
            NSLog(@"登录成功");
        } failed:^(NSString *module, int errId, NSString *errMsg) {
            NSLog(@"登录失败");
        }];
        
    }else{
        [[ILiveLoginManager getInstance] iLiveLogin:@"32013" sig:@"eJxNj91ugkAQhd9lb9vU-WF1adILo9i0oqQFU3tFiOzC1LIQdl01Td*9QDDp3M05c76Z*UFJGD*Y-JhmTQM5ekTEwxjPvCkW6H4w5aWBVqaZsrLtfMp92k2M5pBKM5uytg-fZAuV7FmcEky4x-ioQy61BQUDiVFM2I1zONQnbVN7beQ-joGi6zbBbvESlDMlJqHnNKby*cq-9-BeudXa3RXs67wQkTm6TbxU2zKaQzA-OV2LyNel-HgNtTrvyeebiKeXIsiIn6hsCdudm6xXVWKexmVOtgZq3f-YHU0ow32h3z-UJVan" succ:^{
            NSLog(@"登录成功");
        } failed:^(NSString *module, int errId, NSString *errMsg) {
            NSLog(@"登录失败");
        }];
    }
    
}

-(void)loginWithUserId:(NSString *)userId sign:(NSString *)sign
{
    
    [[ILiveLoginManager getInstance] iLiveLogin:userId sig:sign succ:^{
        NSLog(@"登录成功");
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        NSLog(@"登录失败");
    }];
    
    
    
    
    
    
    
}

-(void)initSDK
{
    TIMManager *manager = [[ILiveSDK getInstance] getTIMManager];
    //日志
    [manager initLogSettings:NO logPath:[manager getLogPath]];
    [manager setLogLevel:TIM_LOG_ERROR];
    
    [[ILiveSDK getInstance] setLogLevel:ILive_LOG_ERROR];
    [[ILiveSDK getInstance] setConsoleLogPrint:NO];
    //初始化
    int success = [[ILiveSDK getInstance] initSdk:[ShowAppId intValue] accountType:[ShowAccountType intValue]];
    NSLog(@"%d",success);
}


-(void)addIMListener:(id<ILVLiveIMListener>)listener
{
    [[TILLiveManager getInstance] setIMListener:listener];
}

-(void)addAVListener:(id)listener
{
    [[TILLiveManager getInstance] setAVListener:listener];
}

-(void)setAVRootView:(UIView *)avRootView
{
    [[TILLiveManager getInstance] setAVRootView:avRootView];
}

-(void)createRoomWithId:(NSString *)roomId
{
    TILLiveRoomOption *option = [TILLiveRoomOption defaultHostLiveOption];
    
    
    [[TILLiveManager getInstance] createRoom:[roomId intValue] option:option succ:^{
        
        NSLog(@"创建房间成功");
        [[ILiveRoomManager getInstance] setAudioMode:QAVOUTPUTMODE_SPEAKER];
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
        NSLog(@"创建房间失败");
        
    }];
}

-(void)joinRoomWithId:(NSString *)roomId role:(LBAVRole)role
{
    
    TILLiveRoomOption *option;
    if (role == LBAVRoleHost) {
        return;
    }else if (role == LBAVRoleGuest){
        option = [TILLiveRoomOption defaultGuestLiveOption];
        
    }else if (role == LBAVRoleInteractGuest){
        option = [TILLiveRoomOption defaultInteractUserLiveOption];
    }
    
    option.controlRole = [NSString stringWithFormat:@"%d",role];
    
    [[TILLiveManager getInstance] joinRoom:[roomId intValue] option:option succ:^{
        NSLog(@"LiveDemo---> createRoom succ");
        
        [[ILiveRoomManager getInstance] setAudioMode:QAVOUTPUTMODE_SPEAKER];
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        //        if (errId == 10021)//这里做了一个逻辑:创建房间失败，如果是因为群组号被占用，就变成加入房间，以主播角色加入
        //        {
        //            [ws joinRoom];
        //        }
    }];
}

-(void)quitRoom
{
    [[TILLiveManager getInstance] quitRoom:^{
        NSLog(@"quitRoom-->succ");
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        NSLog(@"quitRoom-->fail|M=%@,code=%d,Msg=%@",module,errId,errMsg);
    }];
}

-(void)releaseResouce
{
    [[LBTILiveManager shareManager] quitRoom];
    [[TILLiveManager getInstance] removeAllAVRenderViews];
}


-(void)enableCamera:(BOOL)enable
{
    
    [[ILiveRoomManager getInstance] enableCamera:self.pos enable:enable succ:^{
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
}

- (void)openCamera{
    
    [[LBTILiveManager shareManager] enableCamera:YES];
}

-(void)closeCamera{
    
    [[LBTILiveManager shareManager] enableCamera:NO];
}

- (void)onSwitchCamera{
    
    
    
    
    if (![[ILiveRoomManager getInstance] getCurCameraState]) {
        return;
    }
    
    __weak LBTILiveManager *weakSelf = self;
    
    [[ILiveRoomManager getInstance] switchCamera:^{
        
        weakSelf.pos = [[ILiveRoomManager getInstance] getCurCameraPos];
        NSLog(@"weakSelf.pos %@",@(weakSelf.pos));
        
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    
}


-(void)enalbeMic:(BOOL)enable
{
    [[ILiveRoomManager getInstance] enableMic:enable succ:^{
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
}

- (void)onOpenMic{
    
    [[LBTILiveManager shareManager] enalbeMic:YES];
    
}

-(void)closeMic{
    
    [[LBTILiveManager shareManager] enalbeMic:NO];
}



+ (void)requestAuidoAccessWithHandler:(void (^)(NSError *))handler
{
    AVAuthorizationStatus audioAuthorStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    
    if (AVAuthorizationStatusAuthorized == audioAuthorStatus) {
        handler(nil);
    }else{
        if (AVAuthorizationStatusRestricted == audioAuthorStatus || AVAuthorizationStatusDenied == audioAuthorStatus) {
            NSString *errMsg = NSLocalizedString(@"此应用需要访问麦克风，请设置", @"此应用需要访问麦克风，请设置");
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:errMsg};
            NSError *error = [NSError errorWithDomain:@"访问权限" code:0 userInfo:userInfo];
            handler(error);
        }else{
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        handler(nil);
                    });
                }else{
                    NSString *errMsg = NSLocalizedString(@"不允许访问麦克风", @"不允许访问麦克风");
                    NSDictionary *userInfo = @{NSLocalizedDescriptionKey:errMsg};
                    NSError *error = [NSError errorWithDomain:@"访问权限" code:0 userInfo:userInfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        handler(error);
                    });
                }
            }];
        }
    }
}

+ (void)requestVideoAccessWithHandler:(void (^)(NSError *))handler
{
    AVAuthorizationStatus videoAuthorStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (AVAuthorizationStatusAuthorized == videoAuthorStatus) {
        handler(nil);
    }else{
        if (AVAuthorizationStatusRestricted == videoAuthorStatus || AVAuthorizationStatusDenied == videoAuthorStatus) {
            NSString *errMsg = NSLocalizedString(@"此应用需要访问摄像头，请设置", @"此应用需要访问摄像头，请设置");
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:errMsg};
            NSError *error = [NSError errorWithDomain:@"访问权限" code:0 userInfo:userInfo];
            handler(error);
        }
        else
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        handler(nil);
                    });
                }else{
                    NSString *errMsg = NSLocalizedString(@"不允许访问摄像头", @"不允许访问摄像头");
                    NSDictionary *userInfo = @{NSLocalizedDescriptionKey:errMsg};
                    NSError *error = [NSError errorWithDomain:@"访问权限" code:0 userInfo:userInfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        handler(error);
                    });
                }
            }];
        }
        
    }
}

@end

